package jsu.blogger.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jsu.blogger.mapper.PostMapper;
import jsu.blogger.pojo.BlogPostDetails;
import jsu.blogger.pojo.Draft;
import jsu.blogger.pojo.Post;
import jsu.blogger.pojo.Result;
import jsu.blogger.service.inter.DraftService;
import jsu.blogger.service.inter.PostService;
import jsu.blogger.util.FileUtil;
import jsu.blogger.util.ReturnResultUtil;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.crypto.Data;
import java.io.File;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/draft")
public class DraftController {
    @Autowired
    private DraftService draftService;
    @Autowired
    private PostService postService;
    private static final Logger logger = LoggerFactory.getLogger(DraftController.class);

    //查询用户的草稿 searchUserAllDrafts
    @PostMapping("searchUserAllDrafts")
    public Result searchUserAllBlogs(HttpServletRequest request, HttpServletResponse response) {

        try {
            // 获取请求头中的 uid
            String uidStr = request.getHeader("uid");
            if(uidStr==null) {
                return ReturnResultUtil.failure("uid不能为空");
            }
            //需要token验证
            Map<String, Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
            String userIdStr=String.valueOf(requestBody.get("userId"));
            if(!uidStr.equals(userIdStr)){
                return ReturnResultUtil.failure("用户数据校验异常");
            }
            long userId = Long.parseLong(userIdStr);
            long offset = Long.parseLong(String.valueOf(requestBody.get("offset")));
            long count = Long.parseLong(String.valueOf(requestBody.get("count")));
            if(count<=0|| offset<0){
                return ReturnResultUtil.failure("请求数据异常");
            }
            logger.info("分页查询用户的草稿 --- offset --- count ："+userId+", "+offset+", "+count);
            return ReturnResultUtil.success(draftService.selectDraftsByUserId(userId,count,offset));
        }catch (Exception e){
            return ReturnResultUtil.failure("后端操作异常");
        }
    }


    @PostMapping("deleteDraft")
    public Result  deleteDraft(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取请求头中的 uid
            String uidStr = request.getHeader("uid");
            if(uidStr==null) {
                return ReturnResultUtil.failure("uid不能为空");
            }
            //需要token验证
            Map<String, Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
            String userIdStr=String.valueOf(requestBody.get("userId"));
            if(!uidStr.equals(userIdStr)){
                return ReturnResultUtil.failure("用户数据校验异常");
            }
            long userId = Long.parseLong(userIdStr);
            String draftId = String.valueOf(requestBody.get("draftId"));
            logger.info("删除用户的博客 --- --- 草稿id ："+userId+", "+draftId);
            boolean isDeleted=draftService.deleteDraft(userId,draftId);
            if(!isDeleted){
                return ReturnResultUtil.failure("删除失败");
            }
            return ReturnResultUtil.success();
        }catch (Exception e){
            return ReturnResultUtil.failure("后端操作异常");
        }
    }

    @Autowired
    private PostMapper postMapper;
    // 根据传入的数据查询草稿
    @PostMapping("/searchDraft")
    public Result searchDraft(HttpServletRequest request) {
        Map<String,Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
        String draftId= (String) requestBody.get("draftId");
        //(Long)
        Long userId=Long.parseLong( String.valueOf(requestBody.get("userId")));
        //(Long) requestBody.get("resourceId")
        Long resourceId =Long.parseLong( String.valueOf(requestBody.get("resourceId")));
        logger.info("查询数据 draftId---userId---resourceId"+", "+draftId+", "+userId+", "+resourceId);
        //post方法 根据传的数据查询文本 draftId必须  resourceId可能有 userId必须
        // 验证用户身份
        String validationResult = validateUserAndFile(request, userId);
        if (validationResult != null) {
            return ReturnResultUtil.failure(validationResult);
        }
        //数据校验 draftId是否符合要求 userId 和uid是否相同
        if(!isTemporarySignIdValid(draftId,userId)){
            return ReturnResultUtil.failure("临时标识符验证失败");
        }
        //根据draftId查询
        Draft draft= draftService.getDraftById(draftId);
        Map<String,Object> resultMap=new HashMap<>();
        if(draft==null){
//            return ReturnResultUtil.failure("不存在此草稿");
            draft=new Draft();
            draft.setDraftId("-1");
            draft.setUserId(userId);
            draft.setPostId(resourceId);
        }
            if(draft.getPostId()==null){
                draft.setPostId(-1L);
            }
            //存在 草稿
            if (!draft.getUserId().equals(userId)) {
                return ReturnResultUtil.failure("userId错误");
            }
            // 如果提供了 resourceId（即 postId），且 resourceId 不为 -1，校验 resourceId 是否与草稿中的 postId 一致
            if (!draft.getPostId().equals(resourceId)) {
                return ReturnResultUtil.failure("resourceId错误");
            }

            if("-1".equals(draft.getDraftId())){
                //查询post内容和标题
                Post post=postMapper.getPostTitleAndContentById(resourceId,userId,0);
                if(post!=null){
                    String title=post.getTitle()==null?"":post.getTitle();
                    String content=post.getContent()==null?"":post.getContent();
                    resultMap.put("title",title);
                    resultMap.put("content",content);
                }else {
                    return ReturnResultUtil.failure("数据异常");
                }

            }else {
                //查询数据
                Draft draft1 = draftService.getDraftTitleAndContentById(draftId);
                if (draft1 != null) {
                    String title = draft1.getTitle() == null ? "" : draft1.getTitle();
                    String content = draft1.getContent() == null ? "" : draft1.getContent();
                    resultMap.put("title", title);
                    resultMap.put("content", content);
                } else {
                    return ReturnResultUtil.failure("数据异常");
                }
            }
        return ReturnResultUtil.success(resultMap);
    }

    @PostMapping("/searchDraftOtherDetails")
    public Result searchDraftOtherDetails(HttpServletRequest request) {
        Map<String,Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
        String draftId= (String) requestBody.get("draftId");
        //(Long)
        Long userId=Long.parseLong( String.valueOf(requestBody.get("userId")));
        //(Long) requestBody.get("resourceId")
        Long resourceId =Long.parseLong( String.valueOf(requestBody.get("resourceId")));
        logger.info("查询数据 draftId---userId---resourceId"+", "+draftId+", "+userId+", "+resourceId);
        //post方法 根据传的数据查询文本 draftId必须  resourceId可能有 userId必须
        // 验证用户身份
        String validationResult = validateUserAndFile(request, userId);
        if (validationResult != null) {
            return ReturnResultUtil.failure(validationResult);
        }
        //数据校验 draftId是否符合要求 userId 和uid是否相同
        if(!isTemporarySignIdValid(draftId,userId)){
            return ReturnResultUtil.failure("临时标识符验证失败");
        }
        //根据draftId查询
        Draft draft= draftService.getDraftById(draftId);
        Map<String,Object> resultMap=new HashMap<>();
        if(draft==null){
            return ReturnResultUtil.failure("不存在此草稿");
        }
        if(draft.getPostId()==null){
            draft.setPostId(-1L);
        }
        //存在 草稿
        if (!draft.getUserId().equals(userId)) {
            return ReturnResultUtil.failure("userId错误");
        }
        // 如果提供了 resourceId（即 postId），且 resourceId 不为 -1，校验 resourceId 是否与草稿中的 postId 一致
        if (!draft.getPostId().equals(resourceId)) {
            return ReturnResultUtil.failure("resourceId错误");
        }
        //查询数据
        Draft draft1=draftService.getDraftOtherDetailsById(draftId);
        if(draft1!=null){
           String articleType=draft1.getArticleType()==null?"":draft1.getArticleType();
           String originalUrl=draft1.getOriginalUrl()==null?"":draft1.getOriginalUrl();
            String coverOption=draft1.getCoverOption()==null?"":draft1.getCoverOption();
            String description=draft1.getDescription()==null?"":draft1.getDescription();
            List<String> tagsNames=draft1.getTags()==null? new ArrayList<>() :draft1.getTags();
           resultMap.put("articleType",articleType);
           resultMap.put("originalUrl",originalUrl);
           resultMap.put("tagsNames",tagsNames);
           logger.info("标签:"+tagsNames);
           resultMap.put("description",description);
           resultMap.put("coverOption",coverOption);
           //
        }else {
            return ReturnResultUtil.failure("数据异常");
        }
        return ReturnResultUtil.success(resultMap);
    }
//    private Result handleNoExists(Map<String,Object> requestBody){
//
//    }
    @PostMapping("/saveDraft")
    public Result saveDraft(HttpServletRequest request) {
        Map<String,Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
        String draftId= (String) requestBody.get("draftId");
        long userId=Long.parseLong( String.valueOf(requestBody.get("userId")));
        long resourceId =Long.parseLong( String.valueOf(requestBody.get("resourceId")));
        String title=(String) requestBody.get("title");
        String content = (String) requestBody.get("content"); // 获取内容
        String description=(String) requestBody.get("description");//获取相关描述
        //logger.info("描述---"+description);
        String coverOption = (String) requestBody.get("coverOption"); // 获取有无封面
        String articleType = (String) requestBody.get("articleType"); // 获取文章类型
        String  originalUrl= (String) requestBody.get("originalUrl"); // 获取原文地址
        List<String> saveedTags = (List<String>) requestBody.get("saveedTags"); // 获取标签
        //数据是否符合
        String validationResult = validateUserAndFile(request, userId);
        if (validationResult != null) {
            return ReturnResultUtil.failure(validationResult);
        }
        //数据校验 draftId是否符合要求 userId 和uid是否相同
        if(!isTemporarySignIdValid(draftId,userId)){
            return ReturnResultUtil.failure("临时标识符验证失败");
        }
        String type = (String) requestBody.get("type"); // 获取存储方式
        Draft newDraft=setNewDraft(type,new Draft(draftId,userId,resourceId,title,content,coverOption,articleType,originalUrl,description,LocalDateTime.now(),saveedTags));
        if(newDraft==null){
            return ReturnResultUtil.failure("数据出现了错误");
        }
        return draftService.saveDraft(newDraft,requestBody);
    }
    private Draft setNewDraft(String type,Draft draft){
       if("saveTitleAndContent".equals(type)){
           draft.setCoverOption(null);
           draft.setArticleType(null);
           draft.setOriginalUrl(null);
           draft.setDescription(null);
           return draft;
       } else if ("saveAll".equals(type) ||"release".equals(type)) {
           String description=draft.getDescription();
           // 处理 null 或空字符串的情况
           if (description != null  && description.length() > 150) {
               draft.setDescription(description.substring(0, 150));
           }
           String coverOption=draft.getCoverOption();
           if(!"single".equals(coverOption) && !"none".equals(coverOption)){
               return null;
           }
           //审查数据  setArticleType ----  original  reprint  translation setOriginalUrl
           String articleType = draft.getArticleType();
           if ((!"original".equals(articleType) && !"reprint".equals(articleType) && !"translation".equals(articleType))) {
               return  null;
           }

           // 如果 ArticleType 为 'reprint'，检查 OriginalUrl 是否不为空
           if ("reprint".equals(articleType)) {
               String originalUrl = draft.getOriginalUrl();
               if (originalUrl == null || originalUrl.trim().isEmpty()) {
                   return null;
               }
           }
           if(draft.getTags().isEmpty()){
               return null;
           }
           return draft;
       }
       return null;
    }



    private String validateUserAndFile(HttpServletRequest request, Long userId) {
        // 处理 userId，获取请求头中的 uid 并进行比较
        String uidHeader = request.getHeader("uid"); // 获取请求头中的 uid
        Long uidFromHeader = (uidHeader != null) ? Long.valueOf(uidHeader) : null;
        // 比较 userId 和 uid
        if (uidFromHeader == null || !uidFromHeader.equals(userId)) {
            return "用户身份验证失败";
        }
        return null; // 如果验证通过，返回 null
    }
    private boolean isTemporarySignIdValid(String signId,Long userId) {
        // 验证临时 postId 中的下划线部分  时间戳_userId_随机值
        String[] postIdParts = signId.split("_");
        if (postIdParts.length < 3) {
            logger.error("临时 postId 格式不正确: " + signId);
            return false;
        }
        // 获取 postId 中的第二个数字
        String userIdFromPostId = postIdParts[1];
        if (!userIdFromPostId.equals(String.valueOf(userId))) {
            logger.error("postId 中的用户 ID 必须与提供的 userId 相同: " + signId);
            return false;
        }
        // 日志记录
       // logger.info("临时标识符 验证成功 ---- 用户 userId: " + userId + ", signId: " + signId);
        return true;
    }
}
//            //不存在此草稿
//            if(resourceId<=0){
//                return ReturnResultUtil.failure("resourceId错误");
//            }
//            //查询postId的数据
//            Post post = postService.getPostTitleAndContentById(resourceId, userId,0);
//            //System.out.println(post);
//            if (post != null) {
//                String title = post.getTitle() == null ? "" : post.getTitle();
//                String content = post.getContent() == null ? "" : post.getContent();
//                resultMap.put("title", title);
//                resultMap.put("content", content);
//            }else{
//                return ReturnResultUtil.failure("resourceId错误");
//            }